package com.easycms.common;

import java.util.ArrayList;
import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import com.easycms.entity.CmsUser;
import com.easycms.entity.Role;
import com.easycms.service.CmsUserService;

@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {

	@Autowired
	private CmsUserService cmsUserService;
	@Override
	public Authentication authenticate(Authentication authentication)
			throws AuthenticationException {
		String username = authentication.getName();
		String password = (String) authentication.getCredentials();

		CmsUser cmsUser = cmsUserService.findByName(username);
		System.out.println("------------1111111111111111111111111111-----------");
		if (cmsUser == null) {
			throw new BadCredentialsException("Username not found.");
		}
		System.out.println("------------password=" + password + "-----------");
		System.out.println("------------cmsUser.getPassword()=" + cmsUser.getPassword() + "-----------");

		if (!MD5.MD5Encode(password).equals(cmsUser.getPassword())) {
			throw new BadCredentialsException("Wrong password.");
		}
		
		System.out.println("------------sdfsadfsadfsadfasdfsdffsdf-----------");
		
		Role r = new Role();
		r.setName("ROLE_USER");
		Collection<GrantedAuthority> roles = new ArrayList<GrantedAuthority>();
		roles.add(r);
		cmsUser.setAuthorities(roles);
		Collection<? extends GrantedAuthority> authorities = cmsUser.getAuthorities();

		return new UsernamePasswordAuthenticationToken(username, password, authorities);
	}

	@Override
	public boolean supports(Class<? extends Object> arg0) {
		return true;
	}

}
